package com.joyzone.weixin.util;

import java.io.UnsupportedEncodingException;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.joyzone.weixin.exception.WeixinException;

public class StringUtil extends StringUtils {
	
	// 转换url中的参数位置
	public static String formatParaUrl(String str, String[] args){
    	for(int i=0; i<args.length; i++){
    		str = str.replaceFirst("#"+(i+1)+"#", args[i]);
    	}
    	return str;
    }
	
	// 字符串转换为json对象
	public static JSONObject stringToJson(String str) throws WeixinException{
		JSONObject data = JSONObject.fromObject(str);
		if(data.has("errcode")){
			int errcode = data.getInt("errcode");
			if(errcode != 0)
				throw new WeixinException(errcode+"",data.getString("errmsg"));
		}
		return data;
	}
	
	// URL编码 (utf-8)
	public static String urlEncodeUTF8(String source){
		String result = source;
		try {
			result = java.net.URLEncoder.encode(source, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
}
